package cn.jn.lhm.netty.part06;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

/**
 * @author lhm 2753914576@qq.com
 * @time 2023/7/19 - 21:59
 **/
@Slf4j
public class EchoServer {
    public static void main(String[] args) {
        new ServerBootstrap()
                .channel(NioServerSocketChannel.class)
                .group(new NioEventLoopGroup(), new NioEventLoopGroup(2))
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel client) throws Exception {
                        client.pipeline().addLast("h1", new StringDecoder());
                        client.pipeline().addLast("h2", new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                String data = (String) msg;
                                log.info("收到客户端[{}]的信息:{}", client, data);
                                // 写出数据
                                client.writeAndFlush(data);
                                super.channelRead(ctx, msg);
                            }
                        });
                        // 字符串转为 ByteBuf
                        client.pipeline().addLast(new StringEncoder());
                    }
                })
                .bind(8080);
    }
}
